package com.yin.myproject.thread.spinlock;

import java.util.Random;

/**
 * @author Eason
 * @create 2018-02-09 10:53
 **/
public class Backoff {
    final Random random;
    private final int minDelay, maxDelay;
    private int limit;

    public Backoff(int min, int max) {
        this.minDelay = min;
        this.maxDelay = max;
        limit = minDelay;
        random = new Random();
    }

    //回退,线程等待一段时间
    public void backOff() throws InterruptedException {
        int delay = random.nextInt(limit);
        limit = Math.max(maxDelay, 2 * limit);
        Thread.sleep(delay);
    }
}
